package com.example.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.common.R;
import com.example.entity.Doctor;
import com.example.entity.vo.doctorVo;
import com.example.service.IDepartmentService;
import com.example.service.IDoctorService;
import com.example.service.IHospitalService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@RequestMapping("/doctor")
@Api(tags = "医生管理模块")
@RestController
@CrossOrigin//跨域访问
@Slf4j
public class DoctorController {

    @Autowired
    IDoctorService doctorService;
    @Autowired
    IDepartmentService departmentService;
    @Autowired
    IHospitalService hospitalService;


    //获取医生列表
    @ApiOperation(value = "查询列表")
    @GetMapping("/query")
    public R list(){
        return R.success(doctorService.list());
    }

    @ApiOperation(value = "查询医生列表")
    @GetMapping("/page")
    public R doctorlist(@RequestParam(required = false) String name,
                        @RequestParam(required = false) Long hosId,
                        @RequestParam(required = false) Long deptId,
                        @RequestParam(defaultValue = "1") int page,
                        @RequestParam(defaultValue = "10") int pageSize) {
        log.info("根据条件分页查询医生信息, 科室ID: {}, 医院ID: {}, 姓名: {}, 页码: {}, 每页大小: {}", deptId, hosId, name, page, pageSize);

        // 创建分页对象
        Page<Doctor> pageInfo = new Page<>(page, pageSize);
        Page<doctorVo> pageInfo1 = new Page<>(page, pageSize);

        // 创建查询条件
        LambdaQueryWrapper<Doctor> queryWrapper = new LambdaQueryWrapper<>();

        // 如果提供了科室ID参数，则添加科室ID查询条件
        if (deptId != null) {
            queryWrapper.eq(Doctor::getDeptId, deptId);
        }

        // 如果提供了姓名参数，则添加姓名查询条件
        if (name != null && !name.isEmpty()) {
            queryWrapper.like(Doctor::getName, name);
        }

        // 如果提供了医院ID参数，则添加医院ID查询条件
        if (hosId != null) {
            queryWrapper.eq(Doctor::getHosId, hosId);
        }

        // 执行分页查询
        doctorService.page(pageInfo, queryWrapper);

        // 将分页查询结果转换为 doctorVo
        List<doctorVo> doctorVoList = pageInfo.getRecords().stream()
                .map(doctor -> {
                    doctorVo vo = new doctorVo();
                    BeanUtils.copyProperties(doctor, vo);
                    // 补充部门和医院信息
                    vo.setDepartmentName(departmentService.getById(doctor.getDeptId()).getName());
                    vo.setHospitalName(hospitalService.getById(doctor.getHosId()).getName());
                    return vo;
                })
                .collect(Collectors.toList());

        // 设置分页信息和转换后的 records
        BeanUtils.copyProperties(pageInfo, pageInfo1, "records");
        pageInfo1.setRecords(doctorVoList);

        // 返回结果
        return R.success(pageInfo1);
    }

    // 根据医生ID获取医生信息
    @ApiOperation(value = "根据医生ID获取医生信息")
    @GetMapping("/selectById")
    public R getById(@RequestParam(required = false) Long id){
        log.info("根据医生ID获取医生信息，医生ID: {}", id);
        return R.success(doctorService.getById(id));
    }


    /**
     * 根据科室ID获取医生信息
     */
    @ApiOperation(value = "根据科室ID获取医生信息")
    @GetMapping("/selectByDeptId")
    public R getDoctor(@RequestParam(required = false) Long deptId) {
        log.info("根据科室ID获取医生信息，科室ID: {}", deptId);

        // 创建查询条件
        LambdaQueryWrapper<Doctor> queryWrapper = new LambdaQueryWrapper<>();

        if (deptId != null) {
            queryWrapper.eq(Doctor::getDeptId, deptId);
        }

        // 执行查询
        List<Doctor> doctorList = doctorService.list(queryWrapper);

        // 判断查询结果
        if (doctorList.isEmpty()) {
            return R.error("该科室暂无医生");
        } else {
            return R.success(doctorService.list(queryWrapper));
        }
    }


    /**
     * 新增医生
     */
    @ApiOperation(value = "新增医生")
    @PostMapping("/add")
    public R addDoctor(Doctor doctor) {
        log.info("新增医生{}", doctor);
        doctor.setPassword("1");
        doctorService.save(doctor);
        return R.success("新增成功");
    }

    /**
     * 修改医生信息
     */
    @ApiOperation(value = "修改医生信息")
    @PutMapping("/update")
    public R updateDoctor(Doctor doctor) {
        log.info("修改医生{}", doctor);

        doctorService.updateById(doctor);
        return R.success("修改成功");
    }

    /**
     * 删除医生
     */
    @ApiOperation(value = "删除医生")
    @DeleteMapping("/{id}")
    public R deleteDoctor(@PathVariable Long id) {
        log.info("删除医生{}", id);
        doctorService.removeById(id);
        return R.success("刪除成功");
    }

    /**
     * 批量删除医生
     */
    @ApiOperation(value = "批量删除医生")
    @DeleteMapping("/batch")
    public R deleteBatch(List<Long> ids) {
        log.info("批量删除医生{}");
        doctorService.removeByIds(ids);
        return R.success("刪除成功");
    }

    /**
     * 导出医生信息
     */
    @ApiOperation(value = "导出医生信息")
    @GetMapping("/export")
    public void export(HttpServletResponse response,
                       @RequestParam(required = false) String name,
                       @RequestParam(required = false) String departmentId,
                       @RequestParam(required = false) Integer status) {
        log.info("导出医生信息");
        List<Doctor> list = doctorService.listDoctor(name, departmentId, status, null, null);
//        R.export(response, list, "医生信息", Doctor.class);
    }

    //医生登录
    @PostMapping("/login")
    public Map<String, Object> doctorlogin(@RequestParam String phone,
                                           @RequestParam String password,
                                           HttpSession httpSession) {
        log.info("医生登录，账号：{}，密码：{}", phone, password);
        LambdaQueryWrapper<Doctor> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Doctor::getPhone, phone).eq(Doctor::getPassword, password);
        Doctor doctor = doctorService.getOne(queryWrapper);

        Map<String, Object> R = new HashMap<>();
        if (doctor != null) {
            R.put("flag", true);
            R.put("role", "doctor"); // 返回医生角色信息
            R.put("doctor", doctor);
            httpSession.setAttribute("doctor", doctor.getId()); // 将医生ID存入Session
        } else {
            R.put("flag", false);
            R.put("message", "账号或密码错误"); // 返回错误信息
        }
        log.info("R:{}", R.toString());
        return R; // 返回JSON对象
    }
}